class ListNode {
  val: number;
  next: ListNode | null;
  constructor(val?: number, next?: ListNode | null) {
    this.val = val === undefined ? 0 : val;
    this.next = next === undefined ? null : next;
  }
}

function reverseList(head: ListNode | null): ListNode | null {
  if (head === null || head.next === null) return head;

  const stack: ListNode[] = [];
  let current: ListNode | null = head;
  while (current) {
    stack.push(current);
    current = current.next;
  }
  let newHead: ListNode = stack.pop()!;
  let newHeadCurrent = newHead;
  while (stack.length) {
    const node = stack.pop()!;
    newHeadCurrent!.next = node;
    newHeadCurrent = newHeadCurrent!.next;
  }
  newHeadCurrent.next = null;

  return newHead;
}

const node = new ListNode(1);
node.next = new ListNode(2);
node.next.next = new ListNode(3);

const reverse = reverseList(node);
let current = reverse;
while (current) {
  console.log(current.val);
  current = current.next;
}

export {};
